<template>
  <r-header />
  <main>
    <router-link to="/">
      <r-logo class="logo" />
    </router-link>

    <!-- 手机号输入 -->
    <div class="line">
      <label class="label">手机</label>
      <div class="combine">
        <input placeholder="请输入手机号" v-model="form.phone_number" @blur="validatePhone"
          :class="{ 'error-border': phoneError }">
        <button @click="sendSmsValidCode" :disabled="countdown > 0 || !form.phone_number"
          :class="{ 'disabled': countdown > 0 || !form.phone_number }">
          {{ countdown > 0 ? `${countdown}s后重发` : '发送验证码' }}
        </button>
      </div>
      <div v-if="phoneError" class="error-text">{{ phoneError }}</div>
    </div>

    <!-- 验证码输入 -->
    <div class="lines">
      <label class="label">验证码</label>
      <input placeholder="请输入6位验证码" v-model="form.valid_code" @blur="validateCode" :class="{ 'error-border': codeError }"
        maxlength="6">
      <div v-if="codeError" class="error-text">{{ codeError }}</div>
    </div>

    <!-- 密码设置 -->
    <div class="lines">
      <label class="label">设置密码</label>
      <input type="password" placeholder="请设置密码（至少6位，包含数字和字母）" v-model="form.password" @blur="validatePassword"
        :class="{ 'error-border': passwordError }">
      <div v-if="passwordError" class="error-text">{{ passwordError }}</div>
    </div>

    <!-- 确认密码 -->
    <div class="lines">
      <label class="label">再次设置密码</label>
      <input type="password" placeholder="请再次输入密码" v-model="form.password_confirm" @blur="validatePasswordConfirm"
        :class="{ 'error-border': passwordConfirmError }">
      <div v-if="passwordConfirmError" class="error-text">{{ passwordConfirmError }}</div>
    </div>

    <!-- 注册按钮 -->
    <button class="button" @click="phoneRegister" :disabled="isLoading">
      <span v-if="isLoading">注册中...</span>
      <span v-else>确认注册</span>
    </button>

    <!-- 已有账号 -->
    <div class="qwq">
      <div>有账号？</div>
      <router-link to="/signin">
        <div class="but">立即登陆→</div>
      </router-link>
    </div>
  </main>
</template>

<script type="text/javascript">
import axios from 'axios';

export default {
  name: "register",
  data() {
    return {
      form: {
        phone_number: "",
        valid_code: "",
        password: "",
        password_confirm: ""
      },
      countdown: 0,
      isLoading: false,
      phoneError: "",
      codeError: "",
      passwordError: "",
      passwordConfirmError: ""
    };
  },
  methods: {
    // 手机号验证
    validatePhone() {
      const phoneReg = /^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/;
      if (!this.form.phone_number) {
        this.phoneError = "请输入手机号";
        return false;
      } else if (!phoneReg.test(this.form.phone_number)) {
        this.phoneError = "请输入有效的手机号";
        return false;
      } else {
        this.phoneError = "";
        return true;
      }
    },

    // 验证码验证
    validateCode() {
      const codeReg = /^\d{6}$/;
      if (!this.form.valid_code) {
        this.codeError = "请输入验证码";
        return false;
      } else if (!codeReg.test(this.form.valid_code)) {
        this.codeError = "请输入6位数字验证码";
        return false;
      } else {
        this.codeError = "";
        return true;
      }
    },

    // 密码验证
    validatePassword() {
      const passwordReg = /^(?=.*[A-Za-z])(?=.*\d).{6,16}$/;
      if (!this.form.password) {
        this.passwordError = "请设置密码";
        return false;
      } else if (!passwordReg.test(this.form.password)) {
        this.passwordError = "密码需6-16位，包含数字和字母";
        return false;
      } else {
        this.passwordError = "";
        return true;
      }
    },

    // 确认密码验证
    validatePasswordConfirm() {
      if (!this.form.password_confirm) {
        this.passwordConfirmError = "请再次输入密码";
        return false;
      } else if (this.form.password !== this.form.password_confirm) {
        this.passwordConfirmError = "两次密码输入不一致";
        return false;
      } else {
        this.passwordConfirmError = "";
        return true;
      }
    },

    // 表单整体验证
    validateForm() {
      const isPhoneValid = this.validatePhone();
      const isCodeValid = this.validateCode();
      const isPasswordValid = this.validatePassword();
      const isPasswordConfirmValid = this.validatePasswordConfirm();

      return isPhoneValid && isCodeValid && isPasswordValid && isPasswordConfirmValid;
    },

    // 发送验证码
    sendSmsValidCode() {
      if (!this.validatePhone()) return;

      this.isLoading = true;
      axios.post('/api/auth/send-sms-code', {
        phone: this.form.phone_number
      })
        .then(response => {
          this.isLoading = false;
          if (response.data.success) {
            // 启动倒计时
            this.startCountdown();
            alert('验证码已发送，请查收:'+ response.data.data);
          } else {
            this.phoneError = response.data.message || '验证码发送失败';
          }
        })
        .catch(error => {
          this.isLoading = false;
          if (error.response) {
            this.phoneError = error.response.data.message || '验证码发送失败';
          } else {
            this.phoneError = '网络连接失败，请检查网络设置';
          }
        });
    },

    // 倒计时功能
    startCountdown() {
      this.countdown = 60;
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },

    // 注册提交
    phoneRegister() {
      if (!this.validateForm()) return;

      this.isLoading = true;
      axios.post('/api/auth/register', this.form)
        .then(response => {
          this.isLoading = false;
          if (response.data.success) {
            // 存储token
            localStorage.setItem('token', response.data.token);
            // 注册成功后直接视为已登录，更新 Vuex，切换头部导航
            this.$store.commit('user/login', {
              phone_number: this.form.phone_number,
              token: response.data.token,
            });
            alert('注册成功');
            this.$router.push('/');
          } else {
            alert(response.data.message || '注册失败，请重试');
          }
        })
        .catch(error => {
          this.isLoading = false;
          if (error.response) {
            // 服务器返回错误
            const errorMsg = error.response.data.message;
            if (errorMsg.includes('手机号')) {
              this.phoneError = errorMsg;
            } else if (errorMsg.includes('验证码')) {
              this.codeError = errorMsg;
            } else {
              alert(errorMsg);
            }
          } else if (error.request) {
            // 网络错误
            alert('网络连接失败，请检查网络设置');
          } else {
            // 其他错误
            alert('注册过程出错，请重试');
          }
        });
    }
  },
  mounted() {
  }
};
</script>

<style lang="scss" scoped>
main {
  display: flex;
  flex-direction: column;
  justify-items: center;
  align-items: center;
  padding: 0rem 1rem 1rem 2rem;

  .line {
    height: auto;
    margin-bottom: 24px;
    color: rgb(255 255 255);

    .label {
      font-size: 0.875rem;
      font-weight: 600;
      color: rgb(255 255 255);
      line-height: 1.5rem;
      height: 24px;
      width: 382px;
    }

    .combine {
      display: flex;
      flex-direction: row;
      justify-content: center;
      height: 40px;
      width: 384px;
      line-height: 1.5rem;

      >input {
        width: 282px;
        height: 40px;
        margin-right: 8px;
        border-radius: 0.375rem;
        background-color: transparent;
        outline: none;
        border-style: solid;
        border: 1px solid white;
        color: rgb(255 255 255);
        font-size: 0.875rem;
        padding: 0 6px;
        margin-top: 8px;

      }

      input:focus {
        background-color: transparent;
        border-color: #37bcf7;
      }

      >button {
        width: 94px;
        height: 40px;
        border-radius: 0.375rem;
        background-color: transparent;
        border: 1px solid white;
        margin-top: 8px;
        outline: none;
        cursor: pointer;
        font-size: 0.875rem;
        font-weight: 600;
        border-style: solid;
        color: #37bcf7;

      }

      button:hover:not(:disabled) {
        background-color: #37bcf7;
        color: rgb(255 255 255);
      }

      button:disabled {
        opacity: 0.7;
        cursor: not-allowed;
      }
    }
  }

  .lines {
    display: flex;
    flex-direction: column;
    height: auto;
    margin-bottom: 24px;

    .label {
      font-size: 0.875rem;
      font-weight: 600;
      color: rgb(255 255 255);
      line-height: 1.5rem;
      height: 24px;
      width: 382px;
    }

    >input {
      height: 40px;
      width: 384px;
      border-radius: 0.375rem;
      background-color: transparent;
      outline: none;
      border-style: solid;
      border: 1px solid white;
      color: rgb(255 255 255);
      padding: 0 6px;
      margin-top: 8px;

    }

    input:focus {
      background-color: transparent;
      border-color: #37bcf7;
    }
  }

  .button {
    height: 40px;
    width: 384px;
    padding: 10px;
    font-size: 0.875rem;
    font-weight: 600;
    color: rgb(255 255 255);
    border: none;
    border-radius: 0.375rem;
    background-color: #334155;
    cursor: pointer;
  }

  button:hover:not(:disabled) {
    background-color: #37bcf7;
  }

  button:disabled {
    background-color: #6c757d;
    cursor: not-allowed;
  }

  .qwq {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-top: 64px;
    height: 40px;
    color: #ffffff;
    font-size: 0.875rem;

    .but {
      margin-left: 16px;
      padding: 10px 16px;
      width: 106px;
      font-size: 0.875rem;
      font-weight: 600;
      color: #37bcf7;
      border: 2px solid #37bcf7;
      border-radius: 0.5rem;
      cursor: pointer;

    }
  }

  .error-text {
    color: #ff4d4f;
    font-size: 0.875rem;
    height: 20px;
    margin-top: 4px;
    margin-left: 2px;
  }

  .error-border {
    border-color: #ff4d4f !important;
  }
}

.logo {
  margin-bottom: 64px;
}

@media screen and (max-width:660px) {
  main {

    .line {

      .label {
        width: 282px;
      }

      .combine {
        width: 282px;
        line-height: 1.5rem;

        >input {
          width: 200px;

        }
      }
    }

    .lines {
      display: flex;
      flex-direction: column;
      height: auto;
      margin-bottom: 24px;

      .label {
        width: 282px;
      }

      >input {
        width: 282px;
      }
    }

    .button {
      width: 282px;
    }
  }
}
</style>